<?php
uses('model');

class mailModel extends Model {

    function __construct() {
        parent::__construct();
    }

    function send($v) {
        $this->dbconnect();

        return $this->db->Insert($this->table['mail'], $v);
    }

    function sendMail($v=null) {
        $this->dbconnect();
        //$this->db->debug();

        /*
        1.发送成功
        2.发送失败
        4.没有要发送的mail
        */

        $all = $this->db->GetAll($this->table['mail'], '*', 'issent=0 AND sendtime < ' .time(). ' ORDER BY id LIMIT 10');
        if ($all) {
            uses('mail');
            $m = new gmail;

            foreach ($all as $rs) {
                $m->AddAddress($rs['mailto'], $rs['sendto']);
                $m->Subject = $rs['subject'];

                //是否HTML
                if ($rs['ishtml']) {
                    $m->IsHTML(true);
                    $m->Body = $rs['body'];
                } else {
                    $m->IsHTML(false);
                    $m->Body = $rs['body'] . "\r\n\r\n--------\r\n乐铺 敬上\r\nLooPo.cn\r\n".date('Y-m-d');
                }

                if ($m->Send()) {
                    $data['code']['sendMail'] = 1;
                    //发送成功
                    //$this->db->Delete($this->table['mail'], "id={$rs['id']}");
                    $this->db->Update($this->table['mail'], array('issent'=>1), "id={$rs['id']}");
                } else {
                    $data['code']['sendMail'] = 2;

                    $data['err'] = $m->ErrorInfo;

                    //发送失败的十分钟后再发
                    $fields['sendtime'] = time() + 600;
                    $fields['err']      = '{[+1]}';
                    $this->db->Update($this->table['mail'], $fields, "id={$rs['id']}");
                }

                $m->ClearAddresses();
            }

            //大于三次的不再发送
            //$this->db->Delete($this->table['mail'], "mailto = ''");
            $this->db->Update($this->table['mail'], array('issent'=>'-1'), "err >= 3");
        } else {
            $data['code']['sendMail'] = 4;
        }

        return $data;
    }
}
?>
